<template>
  <div>
    <el-select
      style="width: 30%"
      placeholder="请输入会员名称"
      v-model="searchValue"
      filterable
      default-first-option
      clearable
    >
      <el-option
        v-for="item in tableData"
        :key="item.id"
        :label="item.name"
        :value="item.name"
      ></el-option>
    </el-select>
    <el-button @click="searchButton">搜索</el-button>
    <el-button style="float: right; border-color: blue" @click="exportTable">导出</el-button>
    <el-button style="float: right" @click="[(dialogFormVisible = true), (isEdit = false)]"
      >添加会员</el-button
    >
  </div>
  <el-table :data="currentPageData" style="width: 100%">
    <el-table-column fixed prop="name" label="会员名称" />
    <el-table-column prop="phone" label="手机号" />
    <el-table-column prop="email" label="邮箱" />
    <el-table-column prop="points" label="积分" />
    <el-table-column fixed="right" label="操作">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
          编辑
        </el-button>
        <el-popconfirm
          title="确定删除该会员吗？"
          @confirm="deleteMenber(scope.row.id)"
          confirm-button-text="确认"
          cancel-button-text="取消"
        >
          <template #reference>
            <el-button link type="primary" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-size="pageSize"
    :page-sizes="[5, 10, 20, 50, 100]"
    layout="total,sizes, prev, pager, next,"
    :total="total"
    style="float: right"
  >
  </el-pagination>
  <el-dialog v-model="dialogFormVisible" title="添加分类" width="500">
    <el-form :model="form" label-width="15%">
      <el-form-item label="会员名称" :label-width="0">
        <el-input v-model="form.name" placeholder="请输入会员名称" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" :label-width="0">
        <el-input v-model="form.phone" placeholder="请输入手机号" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="0">
        <el-input v-model="form.email" placeholder="请输入邮箱" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogSure"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import myAxios from '../../axios/myAxios'
import { onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ExcelJS from 'exceljs'
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
}
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1
}
const form = reactive({
  name: '',
  phone: '',
  email: '',
  points: '',
})
const isEdit = ref(false)
const idForEdit = ref(0)
const dialogFormVisible = ref(false)
const dialogSure = () => {
  if (isEdit.value) {
    myAxios
      .put('/member/update', {
        id: idForEdit.value,
        name: form.name,
        phone: form.phone,
        email: form.email,
        points: form.points,
      })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          init()
        } else {
          ElMessage({
            message: '修改失败',
            type: 'error',
          })
        }
      })
  } else {
    myAxios
      .post('/member/create', {
        name: form.name,
        phone: form.phone,
        email: form.email,
        points: form.points,
      })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          init()
        } else {
          ElMessage({
            message: '添加失败',
            type: 'error',
          })
        }
      })
  }
  form.name = ''
  form.phone = ''
  form.email = ''
  form.points = ''
  dialogFormVisible.value = false
}
const handleClick = (row) => {
  idForEdit.value = row.id
  form.name = row.name
  form.phone = row.phone
  form.email = row.email
  form.points = row.points
  isEdit.value = true
  dialogFormVisible.value = true
}

const deleteMenber = (id: number) => {
  myAxios.delete(`/member/delete/${id}`).then((res) => {
    if (res.data.code === 200) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      init()
    } else {
      ElMessage({
        message: '删除失败',
        type: 'error',
      })
    }
  })
}

const tableData = ref([])
const init = () => {
  myAxios.get('/member/list').then((res) => {
    if (res.data.code === 200) {
      tableData.value = res.data.data.records
      total.value = tableData.value.length
    }
  })
}

const searchValue = ref('')
const searchButton = () => {
  if (searchValue.value === '') {
    init()
  } else {
    myAxios.get(`/member/name/${searchValue.value}`).then((res) => {
      if (res.data.code === 200) {
        const data = [
          {
            id: res.data.data.id,
            name: res.data.data.name,
            phone: res.data.data.phone,
            email: res.data.data.email,
            points: res.data.data.points,
          },
        ]
        tableData.value = data
        total.value = tableData.value.length
      }
    })
  }
}

const exportTable = () => {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('Sheet1')
  worksheet.columns = [
    { header: '会员名称', key: 'name', width: 10 },
    { header: '手机号', key: 'phone', width: 20 },
    { header: '邮箱', key: 'email', width: 20 },
    { header: '积分', key: 'points', width: 10 },
  ]
  tableData.value.forEach((rowData) => {
    worksheet.addRow(rowData)
  })
  workbook.xlsx.writeBuffer().then((buffer) => {
    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '会员列表.xlsx'
    a.click()
  })
}

onMounted(() => {
  init()
})
</script>
